package lucene.server.common.utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

@Component
@Slf4j
public class SpringContextUtil implements ApplicationContextAware {
    private static ApplicationContext context = null;

    /**
     * Spring在初始化IOC时，会调用实现了ApplicationContextAware接口的类，将他的容器对象传给实现方法
     *
     * @param context IOC创建的容器
     */
    @Override
    public void setApplicationContext(ApplicationContext context) {
        SpringContextUtil.setContext(context);
    }

    /**
     * 取得存储在静态变量中的ApplicationContext.
     */
    public static ApplicationContext getContext() {

        if (context == null) {

            throw new IllegalStateException("applicaitonContext未注入");
        }
        return context;

    }

    /**
     * 存储静态变量中的ApplicationContext.
     */
    public static void setContext(ApplicationContext context) {
        SpringContextUtil.context = context;
    }

    /**
     * 从静态变量ApplicationContext中取得Bean, 自动转型为所赋值对象的类型
     */
    public static <T> T getBean(String name) {
        if (context == null){
            throw new IllegalStateException("applicaitonContext未注入");
        }
        try {
            return (T) context.getBean(name);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return (T) null;
    }
    public static <T> T getBean(Class<T> clazz) {
        if (context == null){
            throw new IllegalStateException("applicaitonContext未注入");
        }
        try {
            return (T) context.getBean(clazz);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return (T) null;
    }
}
